package corba_manager;

import java.io.FileInputStream;
import java.util.Properties;

import org.omg.CORBA.Any;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.Servant;

public class CorbaManager {
	private ORB orb;
	private POA rootPOA;
	private NamingContextExt nce;
	private static CorbaManager instance = null;

	private CorbaManager() {
		Properties pro = new Properties(), prop1 = new Properties();
		try {
			pro.load(new FileInputStream("conf/properties.properties"));
			prop1.put("ORBInitialHost", pro.get("ORB_INITIAL_ADDRESS"));
			prop1.put("ORBInitialPort", pro.get("ORB_INITIAL_PORT"));
		} catch (Exception e) {
			System.out.println("CorbaManager : erreur listening");
			e.printStackTrace();
		}
		orb = ORB.init(new String[] {}, pro);
		try {
			rootPOA = POAHelper.narrow(orb
					.resolve_initial_references("RootPOA"));
			rootPOA.the_POAManager().activate();

			nce = NamingContextExtHelper.narrow(orb
					.resolve_initial_references("NameService"));

			new Thread(new Runnable() {
				public void run() {
					orb.run();
				}
			}).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static CorbaManager getInstance() {
		if (instance == null)
			instance = new CorbaManager();
		return instance;
	}

	public Object publish(Servant obj, String name) {
		NameComponent[] ncs = new NameComponent[1];
		ncs[0] = new NameComponent(name, "");
		try {
			Object objRef = rootPOA.servant_to_reference(obj);
			nce.rebind(ncs, objRef);
			return objRef;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Object getReference(String name) {
		try {
			Object obj = nce.resolve_str(name);
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Any createAny() {
		return orb.create_any();
	}

	public void shutdown() {
		orb.shutdown(false);
	}
}
